﻿Imports System.IO
Imports System.IO.File
Imports Cognex.VisionPro.ToolGroup
Imports Cognex.VisionPro.PMAlign
Imports Cognex.VisionPro.CalibFix
Imports Cognex.VisionPro
Imports Cognex.VisionPro.ImageProcessing
Imports System.Math
Imports Cognex.VisionPro.ToolBlock
Imports Cognex.VisionPro.Display
Public Class CogVisionControl
    Public Declare Function SetParent Lib "user32" Alias "SetParent" (ByVal hWndChild As IntPtr, ByVal hWndNewParent As IntPtr) As Integer
    Public Declare Function MoveWindow Lib "user32" (ByVal hwnd As Integer, ByVal x As Integer, ByVal y As Integer, ByVal nWidth As Integer, ByVal nHeight As Integer, ByVal bRepaint As Integer) As Integer

#Region "结构体定义"
    Structure Position
        Dim X As Double
        Dim Y As Double
        ''' <summary>
        ''' me=p
        ''' </summary>
        ''' <param name="p"></param>
        ''' <remarks></remarks>
        Public Sub EqualTo(ByVal p As Position)
            Me.X = p.X
            Me.Y = p.Y
        End Sub
        ''' <summary>
        ''' me=a+b
        ''' </summary>
        ''' <param name="a"></param>
        ''' <param name="b"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function sum(ByVal a As Position, ByVal b As Position)
            Me.X = a.X + b.X
            Me.Y = a.Y + b.Y
            Return Me
        End Function
        ''' <summary>
        ''' me=a-b
        ''' </summary>
        ''' <param name="a"></param>
        ''' <param name="b"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function subtract(ByVal a As Position, ByVal b As Position)
            Me.X = a.X - b.X
            Me.Y = a.Y - b.Y
            Return Me
        End Function
        ''' <summary>
        ''' me=a*b
        ''' </summary>
        ''' <param name="a"></param>
        ''' <param name="b"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function multiply(ByVal a As Position, ByVal b As Position)
            Me.X = a.X * b.X
            Me.Y = a.Y * b.Y
            Return Me
        End Function
        ''' <summary>
        ''' me.x=a.x/b.x,me.Y=a.y/b.y
        ''' </summary>
        ''' <param name="a"></param>
        ''' <param name="b"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function divide(ByVal a As Position, ByVal b As Position)
            Me.X = a.X / b.X
            Me.Y = a.Y / b.Y
            Return Me
        End Function
        ''' <summary>
        ''' me.x=a.x/p,me.Y=a.y/p
        ''' </summary>
        ''' <param name="a"></param>
        ''' <param name="p"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function divide(ByVal a As Position, ByVal p As Double)
            Me.X = a.X / p
            Me.Y = a.Y / p
            Return Me
        End Function
    End Structure

    Structure ImgSize
        Dim Width As Double
        Dim Height As Double
    End Structure

#End Region

#Region "变量定义"
    Dim gTBCheck As Cognex.VisionPro.ToolBlock.CogToolBlock
    Dim tmpfifo1 As CogAcqFifoTool
    Dim tmpPMAlign1 As CogPMAlignTool
    Dim tmpCalibCB As Object '标定工具对象
    Dim CircularPhoto As Boolean
    Dim myImageSharp As CogImageSharpnessTool
    Dim sharpScore As Double
    Dim myFrameGrabber As ICogFrameGrabber
    Dim myFifoContinuous As Cognex.VisionPro.ICogAcqFifo
    Dim Transform As Cognex.VisionPro.ICogTransform2D '转换
    Dim TrainReginPixel_Rectangle, SearchReginPixel_Rectangle As CogRectangleAffine
    Dim TrainReginPixel_Circle, SearchReginPixel_Circle As CogCircle
    '
    Dim TrainRate_Calib As Position '标定转换比率
    Dim TrainHomeAngle_Calib As Double '标定原点旋转角度
    Dim HomeX As Double '原点位置
    Dim HomeY As Double
    Dim originX, originY, originZ, originC As Double

    Dim Rate0 As Double = 511 / 659 '图像与现实框比例

    Dim RateZoom As Double = 1  '显示1 缩放
    Dim FifoImgSize As ImgSize '相机图片大小
    Dim HomePixel As Position '标定原点的像素坐标

    Dim TrainRegin_StartPoint As Position    '训练区域起点坐标
    Dim TrainRegin_endPoint As Position      '训练区域终点坐标

    Dim SearchRegin_StartPoint As Position   '搜索区域起点坐标
    Dim SearchRegin_EndPoint As Position     '搜索区域终点坐标

    Dim centerPixel As Position
    Dim centerDisplay As Position

    Dim GetTrainRegionFlag As Boolean = False
    Dim MoveRegionFlag As Boolean = False
    Dim GetSearchRegionFlag As Boolean = False

    '    Dim RgR As Double
    Dim TrainReginSideX As Double '记录的训练区域像素
    Dim TrainReginSideY As Double

    Dim SearchReginSideX As Double '记录的搜索区域像素 
    Dim SearchReginSideY As Double

    Public RunFlag As Boolean
#End Region

#Region "窗体初始化"
    Private Sub FrmAddProd_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
        InitControl() '初始化控件
        CogRecordDisplay1.PopupMenu = True ' False '右键菜单
        '  CogRecordDisplay1.MouseWheelMode = CogDisplayMouseWheelModeConstants.None
        ComboBox_TrainRegion.SelectedIndex = 0
        ComboBox_SearchRegion.SelectedIndex = 0
        'status 关联diplay
        CogDisplayStatusBarV21.Display = CogRecordDisplay1

    End Sub

    ''' <summary>
    ''' 初始化控件
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub InitControl()

    End Sub

#End Region

#Region "模板初始化"
    ''' <summary>
    ''' 加载标定为CheckerBoard的相机工具
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub LoadCameraTool(ByVal calibName As String, ByVal pmAlignName As String)
        Try
            If gTBCheck IsNot Nothing Then '工具存在

                tmpCalibCB = gTBCheck.Tools.Item(calibName)
                tmpCalibCB.run()
                '加载相机工具1
                tmpfifo1 = gTBCheck.Tools.Item("相机设定")
                tmpPMAlign1 = gTBCheck.Tools.Item(pmAlignName)
                NumericUpDown_Exposure.Text = tmpfifo1.Operator.OwnedExposureParams.Exposure
                tmpPMAlign1.InputImage = tmpCalibCB.OutputImage
                'tmpPMAlign1.SearchRegion = Nothing
                'tmpPMAlign1.Pattern.TrainImageMask = Nothing
                '计算比率

                Dim x1 As Double
                Dim y1 As Double
                Dim x2 As Double
                Dim y2 As Double
                Dim x3 As Double
                Dim y3 As Double
                '计算TOOL 标定比率
                Transform = tmpCalibCB.Calibration.GetComputedUncalibratedFromCalibratedTransform
                Transform.MapPoint(0, 0, HomePixel.X, HomePixel.Y) '获取原点
                Transform.MapPoint(20, 20, x1, y1)
                Transform.MapPoint(-20, -20, x2, y2)
                Transform.MapPoint(20, 0, x3, y3)

                TrainRate_Calib.X = Abs(x1 - x2) / 40
                TrainRate_Calib.Y = Abs(y1 - y2) / 40
                TrainHomeAngle_Calib = Atan2(y3 - HomePixel.Y, x3 - HomePixel.X) / Acos(-1) * 180

                Dim Transform2 As Cognex.VisionPro.CogTransform2DLinear
                Dim scalingx, scalingy, rotionx, rotiony, translationx, translationy As Double
                Transform2 = tmpCalibCB.Calibration.GetComputedUncalibratedFromCalibratedTransform

                Transform2.GetScalingsRotationsTranslation(scalingx, scalingy, rotionx, rotiony, translationx, translationy)

                Transform2.GetScalingsRotationsTranslation(
                    TrainRate_Calib.X, TrainRate_Calib.Y, rotionx, rotiony, HomePixel.X, HomePixel.Y)

                'TrainRate_Calib.Y = TrainRate_Calib.X


                Dim result(2, 1) As Double
                Dim source(2, 1) As Double
                source(0, 0) = 0
                source(0, 1) = 1

                source(1, 0) = 100
                source(1, 1) = 100

                source(2, 0) = 200
                source(2, 1) = 200

                ' result = Transform2.MapPoints(source)
                Dim mycalib As New CogCalibCheckerboard
                'Dim scaling, r, translation As Double
                '  Transform2.GetScalingAspectRotationSkewTranslation(
                'scaling, r, rotionx, rotiony, HomePixel.X, HomePixel.Y)


                '图像尺寸
                tmpfifo1.Run()
                FifoImgSize.Width = tmpfifo1.OutputImage.Width
                FifoImgSize.Height = tmpfifo1.OutputImage.Height
                '计算display与图片缩放比率
                Rate0 = CogRecordDisplay1.Width / FifoImgSize.Width '图像与现实框比例
                '像素中心
                centerPixel.X = FifoImgSize.Width / 2
                centerPixel.Y = FifoImgSize.Height / 2
                '显示框中心
                centerDisplay.X = CogRecordDisplay1.Width / 2
                centerDisplay.Y = CogRecordDisplay1.Height / 2

            Else
                MsgBox("检测工具不存在") '错误信息写入log
            End If
D:
        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace.ToString)
        End Try
    End Sub
    '''' <summary>
    '    ''' 加载标定为NPointToPoint的相机工具
    '    ''' </summary>
    '    ''' <remarks></remarks>
    '    Private Sub LoadCameraTool_NpointToPoint(ByVal calibName As String)
    '        Try
    '            If gTBCheck IsNot Nothing Then '工具存在
    '                tmpCalibNP = gTBCheck.Tools.Item(calibName)
    '                '加载相机工具1
    '                tmpfifo1 = gTBCheck.Tools.Item("相机设定")
    '                tmpPMAlign1 = gTBCheck.Tools.Item("CogPMAlignTool1")
    '                NumericUpDown_Exposure.Text = tmpfifo1.Operator.OwnedExposureParams.Exposure
    '                tmpPMAlign1.SearchRegion = Nothing
    '                tmpPMAlign1.Pattern.TrainImageMask = Nothing
    '                '计算比率
    '                Dim Transform As Cognex.VisionPro.ICogTransform2D
    '                Dim x1 As Double
    '                Dim y1 As Double
    '                Dim x2 As Double
    '                Dim y2 As Double
    '                Dim x3 As Double
    '                Dim y3 As Double
    '                '计算TOOL 标定比率
    '                Transform = tmpCalibNP.Calibration.GetComputedUncalibratedFromCalibratedTransform
    '                Transform.MapPoint(0, 0, HomePixel.X, HomePixel.Y) '获取原点
    '                Transform.MapPoint(20, 20, x1, y1)
    '                Transform.MapPoint(-20, -20, x2, y2)
    '                Transform.MapPoint(20, 0, x3, y3)
    '                TrainRate_Calib = (Abs(x1 - x2) + Abs(y1 - y2)) / 80
    '                TrainHomeAngle_Calib = Atan2(y3 - HomePixel.Y, x3 - HomePixel.X) / Acos(-1) * 180

    '                FifoImgSize.Width = tmpfifo1.OutputImage.Width
    '                FifoImgSize.Height = tmpfifo1.OutputImage.Height
    '                '计算display与图片缩放比率
    '                Rate0 = CogRecordDisplay1.Width / FifoImgSize.Width '图像与现实框比例

    '            Else
    '                MsgBox("检测工具不存在") '错误信息写入log
    '            End If
    'D:
    '        Catch ex As Exception
    '            MsgBox(ex.Message & ex.StackTrace.ToString)
    '        End Try
    '    End Sub

#End Region

#Region "按钮事件"
    ''' <summary>
    ''' 连续取像
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Button_TakePhoto1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button_TakePhoto.Click

        CircularPhotography()
        
    End Sub

    ''' <summary>
    ''' 曝光修改
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub NumericUpDown1_ValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles NumericUpDown_Exposure.ValueChanged
        Try
            'tmpfifo1.Operator.OwnedExposureParams.Exposure = CDbl(NumericUpDown_Exposure.Value)
            'If myFifoContinuous IsNot Nothing Then
            '    myFifoContinuous.OwnedExposureParams.Exposure = CDbl(NumericUpDown_Exposure.Value)
            'End If
            If tmpfifo1.Operator IsNot Nothing Then
                tmpfifo1.Operator.OwnedExposureParams.Exposure = CDbl(NumericUpDown_Exposure.Value)
            End If
        Catch ex As Exception
            MsgBox("错误:" & ex.Message.ToString)
        End Try
    End Sub
    ''' <summary>
    ''' 绘制搜索区域
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Button_SeclectSearchRegion_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button_SeclectSearchRegion.Click
        Try
            If GetSearchRegionFlag = True Then
                GetSearchRegionFlag = False
                Button_SeclectSearchRegion.BackColor = Color.WhiteSmoke
                Button_SeclectSearchRegion.UseVisualStyleBackColor = True
            Else
                GetSearchRegionFlag = True
                Button_SeclectSearchRegion.BackColor = Color.Lime
                Button_Pointer.BackColor = Color.WhiteSmoke
                Button_Pointer.UseVisualStyleBackColor = True
                Button_MovCenter.BackColor = Color.WhiteSmoke
                Button_MovCenter.UseVisualStyleBackColor = True
                GetTrainRegionFlag = False
                'MoveRegionFlag = False

            End If

            tmpfifo1.Run() '相机运行

            tmpCalibCB.Run() '标定工具运行
            tmpPMAlign1.InputImage = tmpCalibCB.OutputImage
            '  CogRecordDisplay1.MouseMode = CogDisplayMouseModeConstants.Pointer
            If GetSearchRegionFlag = True Then
                ShowCognexRegion(False, True)
            Else
                ShowCognexRegion(False, False)
            End If

            DrawCenterLine(CogRecordDisplay1, FifoImgSize)

        Catch ex As Exception
            MsgBox("错误：" & ex.Message.ToString)
        End Try
    End Sub

    ''' <summary>
    ''' 绘制训练区域按钮
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Button_Pointer_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button_Pointer.Click
        Try
            If GetTrainRegionFlag = True Then
                GetTrainRegionFlag = False
                Button_Pointer.BackColor = Color.WhiteSmoke
                Button_Pointer.UseVisualStyleBackColor = True
            Else
                GetTrainRegionFlag = True
                Button_Pointer.BackColor = Color.Lime
                Button_SeclectSearchRegion.BackColor = Color.WhiteSmoke
                Button_SeclectSearchRegion.UseVisualStyleBackColor = True
                Button_MovCenter.BackColor = Color.WhiteSmoke
                Button_MovCenter.UseVisualStyleBackColor = True
                GetSearchRegionFlag = False
                '  MoveRegionFlag = False
            End If

            tmpfifo1.Run() '相机运行

            tmpCalibCB.Run() '标定工具运行
            tmpPMAlign1.InputImage = tmpCalibCB.OutputImage

            If GetTrainRegionFlag = True Then
                ShowCognexRegion(True, False)
            Else
                ShowCognexRegion(False, False)
            End If
            DrawCenterLine(CogRecordDisplay1, FifoImgSize)
        Catch ex As Exception
            MsgBox("错误：" & ex.Message.ToString)
        End Try
    End Sub

    ''' <summary>
    ''' 移动区域按钮
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Button_MovCenter_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button_MovCenter.Click
        Try
            If Button_MovCenter.BackColor = Color.Lime Then
                MoveRegionFlag = False
                Button_MovCenter.BackColor = Color.WhiteSmoke
                Button_MovCenter.UseVisualStyleBackColor = True
            Else
                MoveRegionFlag = True
                Button_MovCenter.BackColor = Color.Lime
                Button_SeclectSearchRegion.BackColor = Color.WhiteSmoke
                Button_SeclectSearchRegion.UseVisualStyleBackColor = True
                Button_Pointer.BackColor = Color.WhiteSmoke
                Button_Pointer.UseVisualStyleBackColor = True
                GetTrainRegionFlag = False
                GetSearchRegionFlag = False
            End If

            CogRecordDisplay1.MouseMode = CogDisplayMouseModeConstants.Pointer


        Catch ex As Exception

        End Try
    End Sub

    ''' <summary>
    ''' 训练触发按钮
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Button_Train_Click_1(ByVal sender As Object, ByVal e As EventArgs) Handles Button_Train.Click
        Try
            'Dim Type As String = ComboBox_TrainRegion.SelectedItem.ToString
            ''训练区域指定
            'Select Case Type
            '    Case "矩形"
            '        RaginChangeByCalib_Rectangle(TrainReginPixel_Rectangle, tmpPMAlign1, 0)
            '    Case "圆形"
            '        RaginChangeByCalib_Circle(TrainReginPixel_Circle, tmpPMAlign1, 0)
            'End Select

            'Dim SearchType As String = ComboBox_TrainRegion.SelectedItem.ToString
            'Select Case SearchType
            '    Case "矩形"
            '        RaginChangeByCalib_Rectangle(TrainReginPixel_Rectangle, tmpPMAlign1, 1)
            '    Case "圆形"
            '        RaginChangeByCalib_Circle(TrainReginPixel_Circle, tmpPMAlign1, 1)
            '    Case Else
            'End Select
            '  Dim oGraphics As New CogPointMarker
            Dim trainRegion As Object = tmpPMAlign1.Pattern.TrainRegion
            If trainRegion IsNot Nothing Then
                Try
                    tmpPMAlign1.Pattern.Origin.TranslationX = trainRegion.CenterX
                    tmpPMAlign1.Pattern.Origin.TranslationY = trainRegion.CenterY
                Catch ex As Exception
                    If MsgBox("警告：训练原点不在训练中心请确认搜索区域是否为Circle或RectangleAffine，" & vbCrLf &
                              "如果正确，请忽略此信息，点击YES继续！", MsgBoxStyle.YesNo) = MsgBoxResult.No Then
                        GoTo d
                    End If
                End Try
            End If

            tmpPMAlign1.Pattern.Train()
            RunTool(False)

d:
        Catch ex As Exception
            MsgBox("错误:" & ex.Message.ToString)
        End Try
    End Sub

#End Region

#Region "Display按钮操作"

    ''' <summary>
    ''' 鼠标按下获取起始点位
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub CogRecordDisplay1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) ' Handles CogRecordDisplay1.MouseDown
        Try
            If e.Button = Windows.Forms.MouseButtons.Left Then
                '点击的位置
                Dim curMousePos As Position
                curMousePos.X = CogRecordDisplay1.PointToClient(MousePosition).X
                curMousePos.Y = CogRecordDisplay1.PointToClient(MousePosition).Y
                '图像像素平移量
                Dim panDsply As Position
                panDsply.X = CogRecordDisplay1.PanX
                panDsply.Y = CogRecordDisplay1.PanY
                '选择的像素位置Ratio0=display.zoom
                Rate0 = CogRecordDisplay1.Zoom
                Dim selectPixel As Position
                selectPixel = MousePointToPixelPoint(centerDisplay, curMousePos, panDsply, Rate0)
                If GetSearchRegionFlag = True Then
                    SearchRegin_StartPoint.EqualTo(selectPixel)
                Else
                    TrainRegin_StartPoint.EqualTo(selectPixel)
                End If
            End If
        Catch ex As Exception

        End Try
    End Sub

    ''' <summary>
    ''' 鼠标移动获取终点或移动中心点
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub CogRecordDisplay1_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs) 'Handles CogRecordDisplay1.MouseMove
        Try

            If GetTrainRegionFlag = True Or GetSearchRegionFlag = True Or MoveRegionFlag = True Then
                '#######################
                '点击的位置
                Dim curMousePos As Position
                curMousePos.X = CogRecordDisplay1.PointToClient(MousePosition).X
                curMousePos.Y = CogRecordDisplay1.PointToClient(MousePosition).Y
                '图像像素平移量
                Dim panDsply As Position
                panDsply.X = CogRecordDisplay1.PanX
                panDsply.Y = CogRecordDisplay1.PanY
                '选择的像素位置Ratio0=display.zoom
                Rate0 = CogRecordDisplay1.Zoom
                Dim selectPixel As Position
                selectPixel = MousePointToPixelPoint(centerDisplay, curMousePos, panDsply, Rate0)

                '#######################

                If GetTrainRegionFlag = False And GetSearchRegionFlag = False Then
                    '如果不是选择区域，跳转至移动区域
                    GoTo IsMoveRegion
                End If
                If GetTrainRegionFlag = True Then
                    '绘制训练区域终点
                    TrainRegin_endPoint.EqualTo(selectPixel)

                ElseIf GetSearchRegionFlag = True Then
                    '绘制搜索区域终点
                    SearchRegin_EndPoint.EqualTo(selectPixel)

                End If

                If e.Button = Windows.Forms.MouseButtons.Left Then
                    If GetTrainRegionFlag = True Then
                        '训练区域
                        If ComboBox_TrainRegion.SelectedIndex <> -1 Then '有选择
                            Dim type As String = ComboBox_TrainRegion.SelectedItem.ToString
                            If type = "矩形" Then
                                GetRegion2(CogRecordDisplay1, type,
                                            TrainRegin_StartPoint, TrainRegin_endPoint, True,
                                           TrainReginSideX, TrainReginSideY, TrainReginPixel_Rectangle)
                            Else
                                GetRegion2(CogRecordDisplay1, type,
                                            TrainRegin_StartPoint, TrainRegin_endPoint, True,
                                             TrainReginSideX, TrainReginSideY, TrainReginPixel_Circle)
                            End If
                        End If
                    ElseIf GetSearchRegionFlag = True Then
                        '搜索区域
                        If ComboBox_SearchRegion.SelectedIndex <> -1 Then '有选择
                            Dim type As String = ComboBox_SearchRegion.SelectedItem.ToString
                            If type = "矩形" Then
                                GetRegion2(CogRecordDisplay1, type,
                                            SearchRegin_StartPoint, SearchRegin_EndPoint, False,
                                            SearchReginSideX, SearchReginSideY, SearchReginPixel_Rectangle)
                            ElseIf type = "圆形" Then
                                GetRegion2(CogRecordDisplay1, type,
                                            SearchRegin_StartPoint, SearchRegin_EndPoint, False,
                                             SearchReginSideX, SearchReginSideY, SearchReginPixel_Circle)
                            Else
                                '全图
                            End If
                        End If
                    End If

                End If

IsMoveRegion:
                If MoveRegionFlag = False Then
                    GoTo E
                End If
                '移动搜索区域
                If e.Button = Windows.Forms.MouseButtons.Left Then
                    TrainRegin_StartPoint.EqualTo(selectPixel)
                    If ComboBox_TrainRegion.SelectedIndex <> -1 Then '有选择
                        Dim str As String = ComboBox_TrainRegion.SelectedItem.ToString
                        GetStartPoint2(CogRecordDisplay1, str, TrainReginSideX, TrainReginSideY)
                    End If
                End If
            End If

E:
            Dim x As Double
            Dim y As Double
            CogRecordDisplay1.GetImagePanAnchor(x, y, Cognex.VisionPro.Display.CogDisplayPanAnchorConstants.Absolute)

            ' CogRecordDisplay1.GetTransform("", "")
            '绘制中心线
            DrawCenterLine(CogRecordDisplay1, FifoImgSize)
            TextBox_X.Text = Format(TrainRegin_StartPoint.X, "0.00") & "," & Format(TrainRegin_StartPoint.Y, "0.00")
            TextBox_Y.Text = Format(TrainRegin_endPoint.X, "0.00") & "," & Format(TrainRegin_endPoint.Y, "0.00")
            TextBox_R.Text = Format(x, "0.0") & "," & Format(y, "0.0")

        Catch ex As Exception

        End Try
    End Sub

#End Region

#Region "内部算法"
    Private Function MousePointToPixelPoint(ByVal centerDsply As Position,
                                            ByVal curMousePos As Position,
                                            ByVal panDsply As Position,
                                            ByVal Ratio As Double) As Position
        '点击的像素位置
        Dim selectPixel As Position
        ''点击的位置
        'Dim curMousePos As Position
        'curMousePos.X = CogRecordDisplay1.PointToClient(MousePosition).X
        'curMousePos.X = CogRecordDisplay1.PointToClient(MousePosition).Y

        '鼠标位置相对Display中心偏差
        Dim offsetMousePos As Position
        offsetMousePos.subtract(curMousePos, centerDsply)

        '选择位置偏差转换至像素偏差值
        Dim offsetPixel As Position
        offsetPixel.divide(offsetMousePos, Ratio)

        '图像像素平移量
        'Dim panPixel As Position
        'panPixel.X = CogRecordDisplay1.PanX
        'panPixel.Y = CogRecordDisplay1.PanY
        '总偏移量
        Dim totalOffset As Position
        totalOffset.subtract(offsetPixel, panDsply)

        '选择的像素位置
        selectPixel.sum(totalOffset, centerPixel)


        Return selectPixel

    End Function
    ''' <summary>
    ''' 循环拍照
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub CircularPhotography()
        Try
            If Button_TakePhoto.Text = "连续取像" Then
                'CogRecordDisplay1.DrawingEnabled = False
                NumericUpDown_Exposure.Enabled = True
                CogRecordDisplay1.Fit()
                '开启取像
                CircularPhoto = True
                Timer1.Enabled = True

                RunFlag = True
                'tmpfifo1.Run()
                'Dim VIDEO_FORMAT As String = "Generic GigEVision (Mono)"

                'myFrameGrabber = tmpfifo1.Operator.FrameGrabber

                'myFifoContinuous = myFrameGrabber.CreateAcqFifo(
                '    VIDEO_FORMAT, Cognex.VisionPro.CogAcqFifoPixelFormatConstants.Format8Grey, 0, False)
                ''曝光
                'NumericUpDown_Exposure.Value = tmpfifo1.Operator.OwnedExposureParams.Exposure
                'myFifoContinuous.OwnedExposureParams.Exposure = CDbl(NumericUpDown_Exposure.Value)

                '' 连续取像()
                'CogRecordDisplay1.StartLiveDisplay(myFifoContinuous, False)

                ' CogRecordDisplay1.StartLiveDisplay(tmpfifo1.Operator, False)

                CogRecordDisplay1.Fit()
                Button_TakePhoto.Text = "停止取像"
                Button_TakePhoto.BackColor = Color.Lime
                GroupBox2.Visible = False
                DrawCenterLine(CogRecordDisplay1, FifoImgSize)
            Else
                Timer1.Enabled = False

                NumericUpDown_Exposure.Enabled = False
                GroupBox2.Visible = True
                Button_TakePhoto.Text = "连续取像"
                ' CogRecordDisplay1.StopLiveDisplay()
                CircularPhoto = False

                Button_TakePhoto.BackColor = Color.WhiteSmoke
                Button_TakePhoto.UseVisualStyleBackColor = True
                CogRecordDisplay1.DrawingEnabled = True
                CogRecordDisplay1.Fit()

                RunFlag = False
            End If

        Catch ex As Exception
            MsgBox("错误:" & ex.Message.ToString)
        End Try
    End Sub


    ''' <summary>
    ''' 获取起点坐标/中心坐标
    ''' </summary>
    ''' <param name="DisPlay">CogRecordDisplay</param>
    ''' <param name="PMAlign">CogPMAlignTool</param>
    ''' <param name="TYPE">区域形状</param>
    ''' <param name="C_X">记录的区域Width 或R</param>
    ''' <param name="C_Y">记录的区域Height</param>
    ''' <remarks></remarks>
    Private Sub GetStartPoint(ByRef DisPlay As CogRecordDisplay, ByRef PMAlign As CogPMAlignTool, ByVal TYPE As String, ByVal C_X As Double, ByVal C_Y As Double)
        Select Case TYPE
            Case "矩形"

                '图像平移量
                Dim pixPanX As Double = DisPlay.PanX
                Dim pixPanY As Double = DisPlay.PanY
                '转换至像素位置
                Dim pixelX1 As String = HomePixel.X + (TrainRegin_StartPoint.X / RateZoom) - pixPanX '329.5 + (TrainRegin_StartPoint.X / RateZoom) - pixPanX
                Dim pixelY1 As String = HomePixel.Y + (TrainRegin_StartPoint.Y / RateZoom) - pixPanY '247 + (TrainRegin_StartPoint.Y / RateZoom) - pixPanY
                ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                '训练区域像素位置               
                Dim TrainRaginPixel As New CogRectangleAffine
                TrainRaginPixel.CenterX = pixelX1
                TrainRaginPixel.CenterY = pixelY1
                If TrainReginSideX > 0 And TrainReginSideY > 0 Then
                    DisPlay.StaticGraphics.Clear()
                    TrainRaginPixel.SideXLength = C_X
                    TrainRaginPixel.SideYLength = C_Y
                    DisPlay.StaticGraphics.Add(TrainRaginPixel, "")

                    '绘制中心点
                    Dim CenterPoint As New CogPointMarker
                    CenterPoint.SizeInScreenPixels = 10 '中心点大小
                    CenterPoint.X = TrainRaginPixel.CenterX
                    CenterPoint.Y = TrainRaginPixel.CenterY
                    DisPlay.StaticGraphics.Add(CenterPoint, "")

                End If

                '训练区域标定位置
                'Dim TrainRaginCalib As New CogRectangleAffine
                'TrainRaginCalib = RaginChangeByCalib_Rectangle(TrainRaginPixel)
                'PMAlign.Pattern.TrainRegion = TrainRaginCalib
                'PMAlign.Pattern.Origin.TranslationX = TrainRaginCalib.CenterX
                'PMAlign.Pattern.Origin.TranslationY = TrainRaginCalib.CenterY

            Case "圆形"

                '图像平移量
                Dim pixPanX As Double = DisPlay.PanX
                Dim pixPanY As Double = DisPlay.PanY
                '转换至像素位置
                Dim pixelX1 As String = HomePixel.X + (TrainRegin_StartPoint.X / RateZoom) - pixPanX
                Dim pixelY1 As String = HomePixel.Y + (TrainRegin_StartPoint.Y / RateZoom) - pixPanY
                '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

                Dim TrainRaginPixel As New CogCircle
                '选取点即原点
                TrainRaginPixel.CenterX = pixelX1
                TrainRaginPixel.CenterY = pixelY1
                If C_X > 0 Then
                    DisPlay.StaticGraphics.Clear()
                    TrainRaginPixel.Radius = C_X
                    DisPlay.StaticGraphics.Add(TrainRaginPixel, "")
                    '绘制中心点
                    Dim CenterPoint As New CogPointMarker
                    CenterPoint.SizeInScreenPixels = 10
                    CenterPoint.X = TrainRaginPixel.CenterX
                    CenterPoint.Y = TrainRaginPixel.CenterY
                    DisPlay.StaticGraphics.Add(CenterPoint, "")

                End If

                '训练区域标定位置
                'Dim TrainRaginCalib As New CogCircle
                'TrainRaginCalib = RaginChangeByCalib_Circle(TrainRaginPixel)

                'If TrainRaginPixel.Radius Then
                '    TrainRaginCalib.Radius = TrainRaginPixel.Radius / TrainRate_Calib.X
                '    PMAlign.Pattern.TrainRegion = TrainRaginCalib
                '    PMAlign.Pattern.Origin.TranslationX = TrainRaginCalib.CenterX
                '    PMAlign.Pattern.Origin.TranslationY = TrainRaginCalib.CenterY
                'End If
        End Select

    End Sub

    ''' <summary>
    ''' 获取起点坐标/中心坐标
    ''' </summary>
    ''' <param name="DisPlay">CogRecordDisplay</param>
    ''' <param name="TYPE">区域形状</param>
    ''' <param name="C_X">记录的区域Width 或R</param>
    ''' <param name="C_Y">记录的区域Height</param>
    ''' <remarks></remarks>
    Private Sub GetStartPoint2(ByRef DisPlay As CogRecordDisplay, ByVal TYPE As String, ByVal C_X As Double, ByVal C_Y As Double)
        Select Case TYPE
            Case "矩形"
                '训练区域像素位置               
                Dim TrainRaginPixel As New CogRectangleAffine
                TrainRaginPixel.CenterX = TrainRegin_StartPoint.X
                TrainRaginPixel.CenterY = TrainRegin_StartPoint.Y
                If TrainReginSideX > 0 And TrainReginSideY > 0 Then
                    DisPlay.StaticGraphics.Clear()
                    TrainRaginPixel.SideXLength = C_X
                    TrainRaginPixel.SideYLength = C_Y
                    DisPlay.StaticGraphics.Add(TrainRaginPixel, "")

                    '绘制中心点
                    Dim CenterPoint As New CogPointMarker
                    CenterPoint.SizeInScreenPixels = 10 '中心点大小
                    CenterPoint.X = TrainRaginPixel.CenterX
                    CenterPoint.Y = TrainRaginPixel.CenterY
                    DisPlay.StaticGraphics.Add(CenterPoint, "")

                End If
                TrainReginPixel_Rectangle = TrainRaginPixel
                '训练区域标定位置
                'Dim TrainRaginCalib As New CogRectangleAffine
                'TrainRaginCalib = RaginChangeByCalib_Rectangle(TrainRaginPixel)
                'PMAlign.Pattern.TrainRegion = TrainRaginCalib
                'PMAlign.Pattern.Origin.TranslationX = TrainRaginCalib.CenterX
                'PMAlign.Pattern.Origin.TranslationY = TrainRaginCalib.CenterY

            Case "圆形"

                Dim TrainRaginPixel As New CogCircle
                '选取点即原点
                TrainRaginPixel.CenterX = TrainRegin_StartPoint.X
                TrainRaginPixel.CenterY = TrainRegin_StartPoint.Y
                If C_X > 0 Then
                    DisPlay.StaticGraphics.Clear()
                    TrainRaginPixel.Radius = C_X
                    DisPlay.StaticGraphics.Add(TrainRaginPixel, "")
                    '绘制中心点
                    Dim CenterPoint As New CogPointMarker
                    CenterPoint.SizeInScreenPixels = 10
                    CenterPoint.X = TrainRaginPixel.CenterX
                    CenterPoint.Y = TrainRaginPixel.CenterY
                    DisPlay.StaticGraphics.Add(CenterPoint, "")

                End If
                TrainReginPixel_Circle = TrainRaginPixel
                '训练区域标定位置
                'Dim TrainRaginCalib As New CogCircle
                'TrainRaginCalib = RaginChangeByCalib_Circle(TrainRaginPixel)

                'If TrainRaginPixel.Radius Then
                '    TrainRaginCalib.Radius = TrainRaginPixel.Radius / TrainRate_Calib.X
                '    PMAlign.Pattern.TrainRegion = TrainRaginCalib
                '    PMAlign.Pattern.Origin.TranslationX = TrainRaginCalib.CenterX
                '    PMAlign.Pattern.Origin.TranslationY = TrainRaginCalib.CenterY
                'End If
        End Select

    End Sub



    ''' <summary>
    ''' 获取形状终点和尺寸
    ''' </summary>
    ''' <param name="DisPlay">CogRecordDisplay</param>
    ''' <param name="PMAlign">CogPMAlignTool</param>
    ''' <param name="TYPE">区域形状</param>
    ''' <param name="C_X">记录绘制区域Width 或R</param>
    ''' <param name="C_Y">记录绘制区域Height</param>
    ''' <remarks></remarks>
    Private Sub GetRegion(ByRef DisPlay As CogRecordDisplay, ByRef PMAlign As CogPMAlignTool, ByVal TYPE As String, ByRef C_X As Double, ByRef C_Y As Double)
        '终点坐标
        TrainRegin_endPoint.X = (DisPlay.PointToClient(MousePosition).X / Rate0 - HomePixel.X)
        TrainRegin_endPoint.Y = (DisPlay.PointToClient(MousePosition).Y / Rate0 - HomePixel.Y)
        Select Case TYPE
            Case "矩形"
                '图像平移量
                Dim pixPanX As Double = DisPlay.PanX
                Dim pixPanY As Double = DisPlay.PanY
                '转换至像素位置
                Dim pixelX1 As String = HomePixel.X + (TrainRegin_StartPoint.X / RateZoom) - pixPanX '329.5 + (TrainRegin_StartPoint.X / RateZoom) - pixPanX
                Dim pixelY1 As String = HomePixel.Y + (TrainRegin_StartPoint.Y / RateZoom) - pixPanY '247 + (TrainRegin_StartPoint.Y / RateZoom) - pixPanY
                ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                Dim pixelX2 As String = HomePixel.X + (TrainRegin_endPoint.X / RateZoom) - pixPanX
                Dim pixelY2 As String = HomePixel.Y + (TrainRegin_endPoint.Y / RateZoom) - pixPanY
                '训练区域像素位置               
                Dim TrainRaginPixel As New CogRectangleAffine
                'TrainRagin.SetFromStartXYEndXY(329.5, 0, 329.5, 247)
                TrainRaginPixel.CenterX = pixelX1 + (pixelX2 - pixelX1) / 2  'regionCenterX
                TrainRaginPixel.CenterY = pixelY1 + (pixelY2 - pixelY1) / 2 'regionCenterY
                If pixelX2 <> pixelX1 And pixelY1 <> pixelY2 Then
                    DisPlay.StaticGraphics.Clear()
                    TrainRaginPixel.SideXLength = Abs(pixelX2 - pixelX1)
                    TrainRaginPixel.SideYLength = Abs(pixelY2 - pixelY1)
                    C_X = TrainRaginPixel.SideXLength '保留X大小
                    C_Y = TrainRaginPixel.SideYLength '保留Y大小
                    DisPlay.StaticGraphics.Add(TrainRaginPixel, "")
                End If
                '显示中心点
                Dim CenterPoint As New CogPointMarker
                CenterPoint.SizeInScreenPixels = 10
                CenterPoint.X = TrainRaginPixel.CenterX
                CenterPoint.Y = TrainRaginPixel.CenterY
                DisPlay.StaticGraphics.Add(CenterPoint, "")

                '转训练区域标定位置
                'Dim TrainRaginCalib As New CogRectangleAffine
                'TrainRaginCalib = RaginChangeByCalib_Rectangle(TrainRaginPixel)

                'PMAlign.Pattern.TrainRegion = TrainRaginCalib
                'PMAlign.Pattern.Origin.TranslationX = TrainRaginCalib.CenterX
                'PMAlign.Pattern.Origin.TranslationY = TrainRaginCalib.CenterY

            Case "圆形"
                '图像平移量
                Dim pixPanX As Double = DisPlay.PanX
                Dim pixPanY As Double = DisPlay.PanY
                '转换至像素位置
                Dim pixelX1 As String = HomePixel.X + (TrainRegin_StartPoint.X / RateZoom) - pixPanX
                Dim pixelY1 As String = HomePixel.Y + (TrainRegin_StartPoint.Y / RateZoom) - pixPanY
                ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                '转换至像素位置
                Dim pixelX2 As String = HomePixel.X + (TrainRegin_endPoint.X / RateZoom) - pixPanX
                Dim pixelY2 As String = HomePixel.Y + (TrainRegin_endPoint.Y / RateZoom) - pixPanY

                Dim TrainRaginPixel As New CogCircle
                '选取点即原点
                TrainRaginPixel.CenterX = pixelX1
                TrainRaginPixel.CenterY = pixelY1
                If pixelX2 <> pixelX1 And pixelY1 <> pixelY2 Then
                    DisPlay.StaticGraphics.Clear()
                    TrainRaginPixel.Radius = Sqrt((pixelX2 - pixelX1) ^ 2 + (pixelY2 - pixelY1) ^ 2)
                    C_X = TrainRaginPixel.Radius '保留半径大小
                    DisPlay.StaticGraphics.Add(TrainRaginPixel, "")
                    '显示中心点
                    Dim CenterPoint As New CogPointMarker
                    CenterPoint.SizeInScreenPixels = 10
                    CenterPoint.X = TrainRaginPixel.CenterX
                    CenterPoint.Y = TrainRaginPixel.CenterY
                    DisPlay.StaticGraphics.Add(CenterPoint, "")
                End If

                '训练区域标定位置
                'Dim TrainRaginCalib As New CogCircle
                'TrainRaginCalib = RaginChangeByCalib_Circle(TrainRaginPixel)

                'If TrainRaginPixel.Radius Then
                '    TrainRaginCalib.Radius = TrainRaginPixel.Radius / TrainRate_Calib.X
                '    PMAlign.Pattern.TrainRegion = TrainRaginCalib
                '    PMAlign.Pattern.Origin.TranslationX = TrainRaginCalib.CenterX
                '    PMAlign.Pattern.Origin.TranslationY = TrainRaginCalib.CenterY
                'End If
        End Select


    End Sub

    ''' <summary>
    ''' 获取形状终点和尺寸
    ''' </summary>
    ''' <param name="DisPlay">CogRecordDisplay</param>
    ''' <param name="TYPE">区域形状</param>
    ''' <param name="C_X">记录绘制区域Width 或R</param>
    ''' <param name="C_Y">记录绘制区域Height</param>
    ''' <remarks></remarks>
    Private Sub GetRegion2(ByRef DisPlay As CogRecordDisplay, ByVal TYPE As String,
                           ByVal StartPoint As Position, ByVal EndPoint As Position, ByVal WithCenter As Boolean,
                           ByRef C_X As Double, ByRef C_Y As Double, ByRef Regin As Object)
        Select Case TYPE
            Case "矩形"
                '训练区域像素位置               
                Dim ReginPixel As New CogRectangleAffine
                Dim RIOLengthPixel As Position
                RIOLengthPixel.subtract(EndPoint, StartPoint)

                Dim RIOCenterOffset As Position
                RIOCenterOffset.divide(RIOLengthPixel, 2)

                Dim RIOCenterPixel As Position
                RIOCenterPixel.sum(StartPoint, RIOCenterOffset)

                ReginPixel.CenterX = RIOCenterPixel.X 'regionCenterX
                ReginPixel.CenterY = RIOCenterPixel.Y 'regionCenterY
                If StartPoint.X <> EndPoint.X And StartPoint.Y <> EndPoint.Y Then
                    DisPlay.StaticGraphics.Clear()
                    ReginPixel.SideXLength = Abs(RIOLengthPixel.X)
                    ReginPixel.SideYLength = Abs(RIOLengthPixel.Y)
                    C_X = ReginPixel.SideXLength '保留X大小
                    C_Y = ReginPixel.SideYLength '保留Y大小
                    DisPlay.StaticGraphics.Add(ReginPixel, "")
                End If
                If WithCenter = True Then
                    '显示中心点
                    Dim CenterPoint As New CogPointMarker
                    CenterPoint.SizeInScreenPixels = 10
                    CenterPoint.X = ReginPixel.CenterX
                    CenterPoint.Y = ReginPixel.CenterY
                    DisPlay.StaticGraphics.Add(CenterPoint, "")
                End If
                '轮廓像素赋值给全局变量记录
                Regin = ReginPixel

            Case "圆形"

                Dim ReginPixel As New CogCircle
                '选取点即原点
                ReginPixel.CenterX = StartPoint.X
                ReginPixel.CenterY = StartPoint.Y

                If StartPoint.X <> EndPoint.X And StartPoint.Y <> EndPoint.Y Then
                    DisPlay.StaticGraphics.Clear()
                    ReginPixel.Radius = Sqrt((EndPoint.X - StartPoint.X) ^ 2 + (EndPoint.Y - StartPoint.Y) ^ 2)
                    C_X = ReginPixel.Radius '保留半径大小
                    DisPlay.StaticGraphics.Add(ReginPixel, "")
                    If WithCenter = True Then
                        '显示中心点
                        Dim CenterPoint As New CogPointMarker
                        CenterPoint.SizeInScreenPixels = 10
                        CenterPoint.X = ReginPixel.CenterX
                        CenterPoint.Y = ReginPixel.CenterY
                        DisPlay.StaticGraphics.Add(CenterPoint, "")
                    End If
                End If
                '轮廓像素赋值给全局变量记录
                Regin = ReginPixel

        End Select
    End Sub

    ''' <summary>
    ''' Circle训练区域转换为标定后区域
    ''' </summary>
    ''' <param name="TrainRaginPixel"></param>
    ''' <remarks></remarks>
    Private Sub RaginChangeByCalib_Circle(ByVal TrainRaginPixel As CogCircle,
                                               ByRef myPMAlign As CogPMAlignTool, ByVal whereRegionIs As Integer)
        '训练区域标定位置
        Dim TrainRaginCalib As New CogCircle
        If TrainHomeAngle_Calib > -2 And TrainHomeAngle_Calib < 2 Then
            TrainRaginCalib.CenterY = -(TrainRaginPixel.CenterY - HomePixel.Y) / TrainRate_Calib.Y
            TrainRaginCalib.CenterX = (TrainRaginPixel.CenterX - HomePixel.X) / TrainRate_Calib.X
        ElseIf TrainHomeAngle_Calib > 88 And TrainHomeAngle_Calib < 92 Then
            TrainRaginCalib.CenterY = (TrainRaginPixel.CenterX - HomePixel.X) / TrainRate_Calib.X
            TrainRaginCalib.CenterX = (TrainRaginPixel.CenterY - HomePixel.Y) / TrainRate_Calib.Y
        ElseIf TrainHomeAngle_Calib > -92 And TrainHomeAngle_Calib < -88 Then
            TrainRaginCalib.CenterY = -(TrainRaginPixel.CenterX - HomePixel.X) / TrainRate_Calib.X
            TrainRaginCalib.CenterX = -(TrainRaginPixel.CenterY - HomePixel.Y) / TrainRate_Calib.Y
        ElseIf TrainHomeAngle_Calib > 178 And TrainHomeAngle_Calib < 182 Then
            TrainRaginCalib.CenterY = (TrainRaginPixel.CenterY - HomePixel.X) / TrainRate_Calib.X
            TrainRaginCalib.CenterX = -(TrainRaginPixel.CenterX - HomePixel.Y) / TrainRate_Calib.Y
        End If

        If TrainRaginPixel.Radius Then
            TrainRaginCalib.Radius = TrainRaginPixel.Radius / TrainRate_Calib.X
        End If
        Dim pixelPosition As Position
        Dim calibPosition As Position
        pixelPosition.X = TrainRaginPixel.CenterX
        pixelPosition.Y = TrainRaginPixel.CenterY
        calibPosition.X = TrainRaginCalib.CenterX
        calibPosition.Y = TrainRaginCalib.CenterY
        '标定位置转换匹配
        calibPosition = BestCalibPoint(pixelPosition, calibPosition)

        TrainRaginCalib.CenterX = calibPosition.X
        TrainRaginCalib.CenterY = calibPosition.Y

        Select Case whereRegionIs
            Case 0
                If TrainRaginPixel.Radius Then
                    TrainRaginCalib.Radius = TrainRaginPixel.Radius / TrainRate_Calib.X
                    myPMAlign.Pattern.TrainRegion = TrainRaginCalib
                    myPMAlign.Pattern.Origin.TranslationX = TrainRaginCalib.CenterX
                    myPMAlign.Pattern.Origin.TranslationY = TrainRaginCalib.CenterY
                End If
            Case 1
                If TrainRaginPixel.Radius Then
                    TrainRaginCalib.Radius = TrainRaginPixel.Radius / TrainRate_Calib.X
                    myPMAlign.SearchRegion = TrainRaginCalib
                End If
        End Select

        '5*7=35




    End Sub

    ''' <summary>
    ''' Rectangle训练区域转换为标定后区域
    ''' </summary>
    ''' <param name="TrainRaginPixel"></param>
    ''' <remarks></remarks>
    Private Sub RaginChangeByCalib_Rectangle(ByVal TrainRaginPixel As CogRectangleAffine,
                                                   ByRef myPMAlign As CogPMAlignTool, ByVal whereRegionIs As Integer)
        '转训练区域标定位置
        Dim TrainRaginCalib As New CogRectangleAffine
        If TrainHomeAngle_Calib > -2 And TrainHomeAngle_Calib < 2 Then
            TrainRaginCalib.CenterX = (TrainRaginPixel.CenterX - HomePixel.X) / TrainRate_Calib.X
            TrainRaginCalib.CenterY = -(TrainRaginPixel.CenterY - HomePixel.Y) / TrainRate_Calib.Y
            If TrainRaginPixel.SideXLength > 0 And TrainRaginPixel.SideYLength > 0 Then
                TrainRaginCalib.SideYLength = TrainRaginPixel.SideYLength / TrainRate_Calib.Y
                TrainRaginCalib.SideXLength = TrainRaginPixel.SideXLength / TrainRate_Calib.X

            End If
        ElseIf TrainHomeAngle_Calib > 88 And TrainHomeAngle_Calib < 92 Then
            TrainRaginCalib.CenterY = (TrainRaginPixel.CenterX - HomePixel.X) / TrainRate_Calib.X
            TrainRaginCalib.CenterX = (TrainRaginPixel.CenterY - HomePixel.Y) / TrainRate_Calib.Y

            If TrainRaginPixel.SideXLength > 0 And TrainRaginPixel.SideYLength > 0 Then
                TrainRaginCalib.SideYLength = TrainRaginPixel.SideXLength / TrainRate_Calib.X
                TrainRaginCalib.SideXLength = TrainRaginPixel.SideYLength / TrainRate_Calib.Y

            End If
        ElseIf TrainHomeAngle_Calib > -92 And TrainHomeAngle_Calib < -88 Then
            TrainRaginCalib.CenterY = -(TrainRaginPixel.CenterX - HomePixel.X) / TrainRate_Calib.X
            TrainRaginCalib.CenterX = -(TrainRaginPixel.CenterY - HomePixel.Y) / TrainRate_Calib.Y
            If TrainRaginPixel.SideXLength > 0 And TrainRaginPixel.SideYLength > 0 Then
                TrainRaginCalib.SideYLength = TrainRaginPixel.SideXLength / TrainRate_Calib.X
                TrainRaginCalib.SideXLength = TrainRaginPixel.SideYLength / TrainRate_Calib.Y

            End If
        ElseIf TrainHomeAngle_Calib > 178 And TrainHomeAngle_Calib < 182 Then
            TrainRaginCalib.CenterY = (TrainRaginPixel.CenterY - HomePixel.Y) / TrainRate_Calib.Y
            TrainRaginCalib.CenterX = -(TrainRaginPixel.CenterX - HomePixel.X) / TrainRate_Calib.X

            If TrainRaginPixel.SideXLength > 0 And TrainRaginPixel.SideYLength > 0 Then
                TrainRaginCalib.SideYLength = TrainRaginPixel.SideYLength / TrainRate_Calib.Y
                TrainRaginCalib.SideXLength = TrainRaginPixel.SideXLength / TrainRate_Calib.X
            End If
        End If

        Dim pixelPosition As Position
        Dim calibPosition As Position
        pixelPosition.X = TrainRaginPixel.CenterX
        pixelPosition.Y = TrainRaginPixel.CenterY
        calibPosition.X = TrainRaginCalib.CenterX
        calibPosition.Y = TrainRaginCalib.CenterY
        '标定位置转换匹配
        calibPosition = BestCalibPoint(pixelPosition, calibPosition)

        TrainRaginCalib.CenterX = calibPosition.X
        TrainRaginCalib.CenterY = calibPosition.Y

        Select Case whereRegionIs
            Case 0
                myPMAlign.Pattern.TrainRegion = TrainRaginCalib
                myPMAlign.Pattern.Origin.TranslationX = TrainRaginCalib.CenterX
                myPMAlign.Pattern.Origin.TranslationY = TrainRaginCalib.CenterY
            Case 1
                myPMAlign.SearchRegion = TrainRaginCalib
        End Select

    End Sub

    ''' <summary>
    ''' 绘制中心线
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub DrawCenterLine(ByRef display As CogRecordDisplay, ByVal fifoSize As ImgSize)
        '659,494
        If CheckBox_ShowCenterLine.Checked = True Then
            If fifoSize.Width > 1 And fifoSize.Height > 1 Then
                Dim myWidth As Double = fifoSize.Width
                Dim myHeight As Double = fifoSize.Height
                Dim LIN1 As New CogLine
                LIN1.SetFromStartXYEndXY(myWidth / 2, 0, myWidth / 2, myHeight)
                display.StaticGraphics.Add(LIN1, "")

                Dim LIN2 As New CogLine
                LIN2.SetFromStartXYEndXY(0, myHeight / 2, myWidth, myHeight / 2)
                display.StaticGraphics.Add(LIN2, "")
            End If
        End If

    End Sub

    ''' <summary>
    ''' 像素空间转换至标定空间
    ''' </summary>
    ''' <param name="pixelPoint">实际选择的像素空间位置</param>
    ''' <param name="calibPoint">初次计算的标定空间位置</param>
    ''' <returns>选择像素对应的最佳标定空间</returns>
    ''' <remarks></remarks>
    Private Function BestCalibPoint(ByVal pixelPoint As Position, ByVal calibPoint As Position) As Position

        Dim mypixelPoint As Position
        Dim mypixelOffset As Position
        Dim OffsetRagin As Position
        Dim bufOffset As Position
        Dim dirX As Integer = 1
        Dim dirY As Integer = 1
        Dim N As Integer = 0
        Try
ComputeAgain:
            '由标定空间转换至像素空间
            Transform.MapPoint(calibPoint.X, calibPoint.Y,
                               mypixelPoint.X, mypixelPoint.Y) '获取原点

            '判断偏差
            mypixelOffset.subtract(pixelPoint, mypixelPoint)

            If Abs(mypixelOffset.X) > 1 Or Abs(mypixelOffset.Y) > 1 Then

                'X校准
                If Abs(mypixelOffset.X) > 1 Then
                    OffsetRagin.X = (mypixelOffset.X / TrainRate_Calib.X)

                    If Abs(OffsetRagin.X) > Abs(bufOffset.X) Then '方向错误,反向
                        dirX = -1 * dirX
                    End If
                    bufOffset.X = OffsetRagin.X

                    If TrainHomeAngle_Calib > -2 And TrainHomeAngle_Calib < 2 Then
                        'TrainRaginCalib.CenterX = X
                        calibPoint.X += dirX * OffsetRagin.X
                    ElseIf TrainHomeAngle_Calib > 88 And TrainHomeAngle_Calib < 92 Then
                        'TrainRaginCalib.CenterY = X
                        calibPoint.Y += dirX * OffsetRagin.X
                    ElseIf TrainHomeAngle_Calib > -92 And TrainHomeAngle_Calib < -88 Then
                        '  TrainRaginCalib.CenterY = -X
                        calibPoint.Y += (-1) * dirX * OffsetRagin.X
                    ElseIf TrainHomeAngle_Calib > 178 And TrainHomeAngle_Calib < 182 Then
                        '   TrainRaginCalib.CenterY =X
                        calibPoint.Y += dirX * OffsetRagin.X
                    End If
                End If
                'Y校准
                If Abs(mypixelOffset.Y) > 1 Then
                    OffsetRagin.Y = (mypixelOffset.Y / TrainRate_Calib.Y)
                    If Abs(OffsetRagin.Y) > Abs(bufOffset.Y) Then '方向错误,反向
                        dirY = -1 * dirY
                    End If
                    bufOffset.Y = OffsetRagin.Y
                    If TrainHomeAngle_Calib > -2 And TrainHomeAngle_Calib < 2 Then
                        'TrainRaginCalib.CenterY = -Y
                        calibPoint.Y += (-1) * dirY * OffsetRagin.Y
                    ElseIf TrainHomeAngle_Calib > 88 And TrainHomeAngle_Calib < 92 Then
                        ' TrainRaginCalib.CenterX =Y
                        calibPoint.X += dirY * OffsetRagin.Y
                    ElseIf TrainHomeAngle_Calib > -92 And TrainHomeAngle_Calib < -88 Then
                        '  TrainRaginCalib.CenterX = -Y
                        calibPoint.X += (-1) * dirY * OffsetRagin.Y
                    ElseIf TrainHomeAngle_Calib > 178 And TrainHomeAngle_Calib < 182 Then
                        '  TrainRaginCalib.CenterX = -Y
                        calibPoint.X += (-1) * dirY * OffsetRagin.Y
                    End If
                End If
                N += 1
                GoTo ComputeAgain
            End If
        Catch ex As Exception
            MsgBox("ERR:" & ex.Message.ToString)
        End Try

        Return calibPoint

    End Function



    ''' <summary>
    ''' 子窗体显示
    ''' </summary>
    ''' <param name="childWindow"></param>
    ''' <remarks></remarks>
    Private Sub ChildFormShow(ByRef childWindow As Form)
        SetParent(childWindow.Handle, Me.Panel1.Handle)
        MoveWindow(childWindow.Handle, 0, 0, Panel1.Width, Panel1.Height, 1)
        childWindow.Show()
    End Sub

    ''' <summary>
    ''' 刷新窗体
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
        Try
            If childFrmFlag = False Then
                Panel2.Visible = True
                CogRecordDisplay1.Visible = True
                CogDisplayStatusBarV21.Visible = True
            End If
        Catch ex As Exception

        End Try
        Try
            If Button_RUN.Text = "停止" Then
                Timer1.Enabled = False
                If RunTool(False) = True Then
                    Timer1.Enabled = True
                End If
            End If
        Catch ex As Exception
            Timer1.Enabled = False
        End Try

        Try
            If CircularPhoto = True Then
                Timer1.Enabled = False
                If RunTool(True) = True Then
                    Timer1.Enabled = True
                End If
            End If
        Catch ex As Exception
            Timer1.Enabled = False
        End Try
    End Sub


#End Region


#Region "高级设置--调用Cognex 控件"

    ''' <summary>
    ''' 相机高级设置
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Button_FifoSet1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button_FifoSet.Click
        Try
            ChildFormShow(FrmFifoTool)
        Catch ex As Exception
            MsgBox("错误：" & ex.Message.ToString)
        End Try
    End Sub

    ''' <summary>
    ''' 训练模板高级设置
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Button_HighTrain1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button_HighTrain.Click
        Try
            CogRecordDisplay1.StopLiveDisplay()
            Button_TakePhoto.Text = "连续取像"
            Button_TakePhoto.BackColor = Color.WhiteSmoke
            Button_TakePhoto.UseVisualStyleBackColor = True

            tmpfifo1.Run()

            tmpCalibCB.inputImage = tmpfifo1.OutputImage
            tmpCalibCB.Run()

            tmpPMAlign1.InputImage = tmpCalibCB.OutputImage
            tmpPMAlign1.Pattern.TrainImage = tmpCalibCB.OutputImage

            'Dim Type As String = ComboBox_TrainRegion.SelectedItem.ToString
            'Select Case Type
            '    Case "矩形"
            '        RaginChangeByCalib_Rectangle(TrainReginPixel_Rectangle, tmpPMAlign1, 0)
            '    Case "圆形"
            '        RaginChangeByCalib_Circle(TrainReginPixel_Circle, tmpPMAlign1, 0)
            'End Select

            'Dim SearchType As String = ComboBox_SearchRegion.SelectedItem.ToString
            'Select Case SearchType
            '    Case "矩形"
            '        RaginChangeByCalib_Rectangle(SearchReginPixel_Rectangle, tmpPMAlign1, 1)
            '    Case "圆形"
            '        RaginChangeByCalib_Circle(SearchReginPixel_Circle, tmpPMAlign1, 1)
            '    Case Else
            '        tmpPMAlign1.SearchRegion = Nothing
            'End Select

            FrmPMAlignTool.CogPMAlignEditV21.Subject = tmpPMAlign1

            ChildFormShow(FrmPMAlignTool)

        Catch ex As Exception
            MsgBox("错误:" & ex.Message.ToString)
        End Try
    End Sub

    ''' <summary>
    ''' 完全模式
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Button_ToolGroup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button_ToolGroup.Click
        Try
            FrmToolGroup.CogToolGroupEditV21.Subject = gTBCheck
            ChildFormShow(FrmToolGroup)
        Catch ex As Exception
            MsgBox("错误：" & ex.Message.ToString)
        End Try
    End Sub

    ''' <summary>
    ''' 添加活动训练区域
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ShowCognexRegion(ByVal ActiveTrainRegion As Boolean, ByVal ActiveSearchRegion As Boolean)
        '清除graphics
        CogRecordDisplay1.Image = tmpPMAlign1.InputImage
        CogRecordDisplay1.Fit()

        CogRecordDisplay1.InteractiveGraphics.Clear()
        CogRecordDisplay1.StaticGraphics.Clear()

        tmpPMAlign1.Pattern.TrainImage = tmpPMAlign1.InputImage
        If ActiveTrainRegion = True Then
            '添加活动训练区域
            CogRecordDisplay1.InteractiveGraphics.Add(
                CType(tmpPMAlign1.Pattern.TrainRegion, ICogGraphicInteractive), "test1", False)
            'Dim originGraphics As New CogPointMarker
            'origingraphics.X = tmpPMAlign1.Pattern.Origin.TranslationX
            'originGraphics.Y = tmpPMAlign1.Pattern.Origin.TranslationY

            'CogRecordDisplay1.InteractiveGraphics.Add(
            '  CType(originGraphics, ICogGraphicInteractive), "test", False)
            ''Else
            '    '添加固定训练区域
            '    CogRecordDisplay1.StaticGraphics.Add(
            '        CType(tmpPMAlign1.Pattern.TrainRegion, ICogGraphic), "test")
        End If

        '添加搜索区域
        If tmpPMAlign1.SearchRegion IsNot Nothing Then

            If ActiveSearchRegion = True Then
                '添加活动搜索区域
                CogRecordDisplay1.InteractiveGraphics.Add(
                    CType(tmpPMAlign1.SearchRegion, ICogGraphicInteractive), "test2", False)
                'Else
                '    '添加固定训练区域
                '    CogRecordDisplay1.StaticGraphics.Add(
                '      CType(tmpPMAlign1.SearchRegion, ICogGraphic), "test")
            End If
        End If

    End Sub


#End Region

#Region "对外接口"

    ''' <summary>
    ''' 保存CogToolBlock工具
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function SaveTBCheck(ByVal path As String)
        Try
            CogSerializer.SaveObjectToFile(gTBCheck, path)
            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function

    ''' <summary>
    ''' 获取CogToolBlock工具
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub ResetTBCheck()
        gTBCheck = New CogToolBlock
    End Sub

    ''' <summary>
    ''' 获取CogToolBlock工具
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetTBCheck() As CogToolBlock
        Return gTBCheck
    End Function


    ''' <summary>
    ''' 传入CogToolBlock工具
    ''' </summary>
    ''' <param name="TBCheck"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function SetTBCheck(ByRef TBCheck As CogToolBlock, ByVal calibName As String, ByVal pmAlignName As String)
        Try
            CogRecordDisplay1.Image = Nothing
            gTBCheck = TBCheck
            LoadCameraTool(calibName, pmAlignName)
            Me.Update()
            Return True

        Catch ex As Exception
            Return False
        End Try

    End Function

    Public Sub Close()
        gTBCheck = Nothing
        Me.Dispose()
    End Sub
#End Region


    Private Sub ComboBox_SearchRegion_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox_SearchRegion.SelectedIndexChanged
        ' Try
        '    Select Case ComboBox_SearchRegion.Text
        '        Case "整张图像"
        '            tmpPMAlign1.SearchRegion = Nothing
        '        Case "圆形"
        '            Dim ReginPixel As New CogCircle
        '            ReginPixel.FitToImage(tmpPMAlign1.InputImage, 1, 1)
        '            tmpPMAlign1.SearchRegion = Nothing
        '            tmpPMAlign1.SearchRegion = CType(ReginPixel, ICogRegion)
        '            tmpPMAlign1.SearchRegion.FitToImage(tmpPMAlign1.InputImage, 0.5, 0.5)
        '        Case "矩形"
        '            Dim ReginPixel As New CogRectangleAffine
        '            tmpPMAlign1.SearchRegion = CType(ReginPixel, ICogRegion)
        '            tmpPMAlign1.SearchRegion.FitToImage(tmpPMAlign1.InputImage, 0.5, 0.5)

        '            Dim PatMaxTrainRegion As New CogRectangleAffine
        '            PatMaxTrainRegion = CType(tmpPMAlign1.Pattern.TrainRegion, CogRectangleAffine)
        '            If PatMaxTrainRegion IsNot Nothing Then
        '                PatMaxTrainRegion.SetCenterLengthsRotationSkew(320, 240, 100, 100, 0, 0)
        '                PatMaxTrainRegion.GraphicDOFEnable = CogRectangleAffineDOFConstants.Position Or CogRectangleAffineDOFConstants.Rotation Or CogRectangleAffineDOFConstants.Size
        '                PatMaxTrainRegion.Interactive = True
        '            End If
        '            'CogRectangle PatMaxSearchRegion = new CogRectangle();
        '            'PatMaxTool.SearchRegion = PatMaxSearchRegion;
        '            'PatMaxSearchRegion.SetCenterWidthHeight(320, 240, 640, 480);
        '            'PatMaxSearchRegion.GraphicDOFEnable = CogRectangleDOFConstants.Position | CogRectangleDOFConstants.Size;
        '            'PatMaxSearchRegion.Interactive = true;



        '    End Select
        'Catch ex As Exception
        '    MsgBox("Err:" & ex.Message.ToString & ex.StackTrace.ToString)
        'End Try
    End Sub

    Private Sub Button_RUN_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button_RUN.Click
        RunTool(False)
        If Button_RUN.Text = "运行" Then
            Button_RUN.Text = "停止"
            Timer1.Enabled = True
        Else
            Button_RUN.Text = "运行"
            Timer1.Enabled = False
        End If
    End Sub
    Private Function RunTool(ByVal justVision As Boolean)
        Try
            'tmpfifo1.Run()
            'tmpCalibCB.Run()
            'tmpPMAlign1.Run()
            gTBCheck.Run()
            CogRecordDisplay1.Image = tmpfifo1.OutputImage
            CogRecordDisplay1.Fit()
            If justVision = False Then

                If tmpfifo1.Operator.FrameGrabber IsNot Nothing Then
                    CogRecordDisplay1.Record = tmpPMAlign1.CreateLastRunRecord
                End If

                If tmpPMAlign1.Results IsNot Nothing Then
                    If tmpPMAlign1.Results.Count > 0 Then
                        TextBox_Score1.Text = Format(tmpPMAlign1.Results.Item(0).Score, "0.000")
                        TextBox_X.Text = Format(tmpPMAlign1.Results.Item(0).GetPose.TranslationX, "0.000")
                        TextBox_Y.Text = Format(tmpPMAlign1.Results.Item(0).GetPose.TranslationY, "0.000")
                        TextBox_R.Text = Format(tmpPMAlign1.Results.Item(0).GetPose.Rotation / Acos(-1) * 180, "0.000")
                    Else
                        TextBox_Score1.Text = "NA"
                        TextBox_X.Text = "NA"
                        TextBox_Y.Text = "NA"
                        TextBox_R.Text = "NA"
                    End If
                Else
                    TextBox_Score1.Text = "NA"
                    TextBox_X.Text = "NA"
                    TextBox_Y.Text = "NA"
                    TextBox_R.Text = "NA"
                End If

            End If

            DrawCenterLine(CogRecordDisplay1, FifoImgSize)
            GetSearchRegionFlag = False
            GetTrainRegionFlag = False
            Return True
        Catch ex As Exception
            TextBox_Score1.Text = "错误"
            MsgBox("Err:" & ex.Message.ToString)
            Return False
        End Try

    End Function
End Class
